<template>
    <div  class="main-container">
        <el-card class="box-card !border-none" shadow="never">
            <el-page-header :content="rule_id ? t('编辑奖励规则') : t('添加奖励规则')" :icon="ArrowLeft" @back="back()" />
        </el-card>

        <el-card class="box-card mt-[15px] !border-none" shadow="never" v-loading="loading">
            <!-- <el-alert type="warning" :closable="false" class="!mb-[20px]">
                <template #default>
                    <p class="mb-[5px]">结算周期：根据计划任务执行，默认一天结算一次</p>
                 </template>
            </el-alert> -->

            <el-form :model="formData" label-width="120px" ref="formRef" :rules="formRules" class="page-form">
                <el-form-item :label="t('奖励规则时间')" prop="rule_time">
                    <div class="w-[180px]">
                        <el-date-picker v-model="formData.rule_time" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"/>
                    </div>
                </el-form-item>
                <el-form-item :label="t('奖励规则类型')" prop="type">
                    <el-radio-group v-model="formData.type">
                        <el-radio :label="1" size="large">{{ t('发布内容') }}</el-radio>
                        <el-radio :label="2" size="large">{{ t('点赞') }}</el-radio>
                        <el-radio :label="3" size="large">{{ t('评论') }}</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="formData.type==1 ? t('发布内容条数量') : formData.type==2 ? t('获赞数量') : t('获评数量')" prop="num">
                    <el-input v-model.trim="formData.num" clearable :placeholder="'请输入'+(formData.type==1 ? t('发布内容条数量') : formData.type==2 ? t('获赞数量') : t('获评数量'))" class="input-width" maxlength="8" show-word-limit />
                </el-form-item>
                <div v-for="item in rules">
                    <component :is="item.edit_component" v-model="formData.rule_json[item.key]" ref="ruleRefs" v-if="item.edit_component"/>
                </div>
                <el-form-item :label="t('状态')" class="page-form">
                <el-switch v-model="formData.status" :active-value="1" :inactive-value="0" />
            </el-form-item>
            </el-form>
            
        </el-card>

        <div class="fixed-footer-wrap">
            <div class="fixed-footer">
                <el-button type="primary" @click="save()">{{ t("save") }}</el-button>
                <el-button @click="back()">{{ t("cancel") }}</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive,defineAsyncComponent} from "vue";
import { t } from "@/lang";
import { useRoute, useRouter } from "vue-router";
import { ArrowLeft } from "@element-plus/icons-vue";
import { FormInstance } from "element-plus";
import {img, filterNumber} from '@/utils/common'
import { getRewardRuleDict,getRewardRuleInfo,addRewardRule,editRewardRule} from '@/addon/sow_community/api/reward_rule'
const start_time = new Date()
const end_time = new Date(new Date().setMinutes(new Date().getMinutes() + 10));
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const rule_id = route.query.rule_id;
const formData = reactive({
    rule_time: [start_time, end_time],
    num:'',
    type:1,
    start_time:'',
    end_time:'',
    rule_json:{},
    status:0
});
const formRef = ref<FormInstance>();

const rules = ref({})
const ruleRefs = ref([])
const modules: any = import.meta.glob('@/**/*.vue')
getRewardRuleDict().then(({ data }) => {
    Object.keys(data).forEach((key: string) => {
        if (modules[data[key].edit_component]) {
            data[key].edit_component && (data[key].edit_component = defineAsyncComponent(modules[data[key].edit_component]))
        } else {
            data.splice(key, 1)
        }
    })
    rules.value = data
})
// 正则表达式
const regExp: any = {
    required: /[\S]+/,
    number: /^\d{0,10}$/,
    digit: /^\d{0,10}(.?\d{0,2})$/,
    special: /^\d{0,10}(.?\d{0,3})$/
}

const formRules = computed(() => {
    return {
        rule_time: [
            {required: true, validator: receiveTime, trigger: 'change'}
        ],
        num: [
            {
                required: true,
                trigger: 'blur',
                validator: (rule: any, value: any, callback: any) => {
                    if (!value) {
                        callback(new Error(t('请输入奖励规则规定数量')))
                    }else if (!regExp.number.test(value)) {
                        callback(new Error(t('格式不正确')))
                    }else if (value <=0) {
                        callback(new Error(t('数量必须大于0')))
                    }else {
                        callback()
                    }
                }
            }
        ],
        type: [{ required: true, message: t("请选择奖励规则类型"), trigger: "blur" }],
    };
});

const receiveTime = (rule: any, value: any, callback: any) => {
    if (!formData.rule_time || (formData.rule_time && !formData.rule_time[0] && !formData.rule_time[1])) {
        callback(new Error(t('selectActivityTime')))
    } else if (!formData.rule_time[0]) {
        callback(new Error(t('selectActivityStartTime')))
    } else if (!formData.rule_time[1]) {
        callback(new Error(t('selectActivityEndTime')))
    } else if (formData.rule_time[1] <= formData.rule_time[0]) {
        callback(new Error(t('selectActivityTimeTips')))
    } else if (formData.rule_time[1] <= new Date()) {
        callback(new Error(t('活动结束时间必须大于当前时间')))
    }

    callback()
}
const formatDateTime = (timestamp: number) => {
    const date = new Date(timestamp * 1000); // 秒转毫秒
    const y = date.getFullYear();
    const m = ('0' + (date.getMonth() + 1)).slice(-2);
    const d = ('0' + date.getDate()).slice(-2);
    const h = ('0' + date.getHours()).slice(-2);
    const min = ('0' + date.getMinutes()).slice(-2);
    const s = ('0' + date.getSeconds()).slice(-2);
    return `${y}-${m}-${d} ${h}:${min}:${s}`;
};

const getRechargePackageInfoFn= () => {
    if (rule_id) {
      // 获取详情
        loading.value = true;
        getRewardRuleInfo(rule_id).then((res) => {
            const data = res.data;
            if (data) {
                Object.assign(formData, data);
                formData.rule_time = [formatDateTime(data.start_time), formatDateTime(data.end_time)]
                loading.value = false;
            }
        })
    }
};

getRechargePackageInfoFn();
const ruleRefsVerify = async () => {
    const refs = ruleRefs.value;
    if (!refs || !refs.length) return true;

    // 验证每一个子组件
    for (const ref of refs) {
        if (ref && typeof ref.verify === 'function') {
            const valid = await ref.verify();
            if (!valid) return false;
        }
    }
    return true;
};

const save = async () => {
    // 触发表单校验
    await formRef.value?.validate(async(valid) => {
        if (valid) {
            const allGiftValid = await ruleRefsVerify();
            if (!allGiftValid) return;
            formData.start_time = formData.rule_time[0];
            formData.end_time = formData.rule_time[1];
            loading.value = true
            if (rule_id) {
                formData.rule_id = Number(rule_id);
                editRewardRule(formData).then((res) => {
                    loading.value = false;
                    back()
                }).catch(() => {
                    loading.value = false;
                });
            } else {
                addRewardRule(formData).then((res) => {
                    loading.value = false;
                    back()
                }).catch(() => {
                    loading.value = false;
                });
            }

        }
    });
};

const back = () => {
    router.push('/sow_community/reward_rule/list')
};
</script>

<style lang="scss" scoped>
.input-width-short{
    width: 190px;
}
</style>
